#!/usr/bin/python
#coding:utf-8 
import os,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  
sys.path.append(BASE_DIR)  # 如果 没有这两句话, vscode 导包找不到 ,太tm狗了
import random
# import cv2
import time
import random 
from PIL import Image  
from Config.Config import Config
# from Util.rsaUtil import RsaEncrypt,DataEncrypt
import base64



# from Commons.filePath import FilePath  
# imgconfig=Config().imgConfig() 
appsetting=Config().appSetting() 
# imgSavePath=FilePath("/static/common/").path()
# bgimgPath=FilePath("/static/bgimg/").path()
# maskimgPath=FilePath("/static/maskimg/").path()


# 图片上传修改控制器
imgconfig=Config().imgConfig() 
# 验证小图
masklist=Config().masklist() 
bglist=Config().bglist()
formatlist=Config().formatlist()  
# rsa=RsaEncrypt() # 生成签名
class ImgController():
    """ 图片上传控制器 """
    def __init__(self,imgPath,maskimgPath,savePath,smallwidth,smallheight,imgurl,height=160,width=260):
        """
        imgPath  获取原图
        savePath 保存切割后的图片
        height   图片压缩后的高度
        width    图片压缩后的宽度
        """
        self.imgPath=imgPath
        self.maskimgPath=maskimgPath
        self.savePath=savePath
        self.height=height
        self.width=width
        self.smallheight=smallheight
        self.smallwidth=smallwidth
        self.imgurl=imgurl
        bg=random.choice(bglist)
        mask=random.choice(masklist)
        self.bg=  Image.open(bg) # 背景图
        self.x=random.randint(95,self.width-70)  # 随机坐标位置X轴生成
        self.y=random.randint(6,self.height-70) # 随机坐标位置Y轴生成
        self.timestamp=round(time.time()*1000000)
        self.mask = Image.open(self.maskimgPath+'mask_{}.png'.format(mask)) # 蒙板
        self.mask_bg = Image.open(self.maskimgPath+'mask_bg_{}.png'.format(mask)) # 蒙板        
        self.mask_img_bg = Image.open(self.maskimgPath+'mask_img_bg_{}.png'.format(mask)) # 蒙板
        #print("坐标轴:x{0} \n坐标轴:y{1}\n蒙版图:{2}\n背景图{3}\n时间戳:{4}".format(self.x,self.y,mask,bg,self.timestamp))
        
    def updateimg(self):
        """
         图片上传方法 
         返回ture 或false
        """
        #self.imgcompress()# 压缩一下

        # 调用裁剪功能
        # def imgcompress(self):
        #     """ 图片压缩
        #     使用OpenCv
        #     暂时不要
        #     """
        # for i in commontlist:
        #     print(i)
        #     image = cv2.imread(i)
        #     img_test2 = cv2.resize(image, (self.width,self.height))  # 等比例缩放到默认宽,高
        #     t = time.time()
        #     imagename=str(round(t * 1000000)) 
        #     cv2.imwrite(self.imgPath+imagename+'.png',img_test2)  # 生成时间戳的文件图片
        #     os.remove(i)
        return True

    def deleteimg(self): 
        commontlist=Config().commontlist() 
        """ 删除 """
        for i in commontlist:
            print(i,"删除图片")
            os.remove(i)
        return True

    def CgetGapDiagramImg(self):
        """
          生成缺口小图
          滑块图片
        """
        x, y = self.x, self.y #随机坐标点
        mask_size = self.mask.size # 获取蒙版图大小
        crop = self.bg.crop((x, y, x + mask_size[0], y + mask_size[1])) # 根据随机坐标点,以及蒙版大小图,获取这个区域的色调(RGB)
        m2 = Image.new('RGBA', self.mask.size) #新建一个图片层, 与蒙版大小一致
        m2.paste(crop, mask=self.mask)  # 将我们crop 获取的色调,复制到新建的蒙版上
        m3 = Image.new('RGBA', m2.size)
        m3.paste(m2, mask=m2)
        shadow = self.mask_bg
        m3.paste(shadow, mask=shadow)
        m3.save(self.savePath+str(self.timestamp)+'.png') # 保存 小的缺口图
        # crop = m3.crop((x, y, x + mask_size[0], y + mask_size[1])) 
        # # 重新生成一个新的图层,跟 bg 一样大
        # bg_shadow=Image.new("RGBA",bg.size,(0,0,0,0)) 
        # bg_shadow.paste(crop,(x,y), mask=self.mask) 
        # img_blender = Image.new('RGBA', bg_shadow.size, (0,0,0,0))
        # bg_shadow = Image.blend(img_blender, bg_shadow, 0.5)
        # r, g, b, alpha = bg_shadow.split()
        # alpha = alpha.point(lambda i: i>0 and 204)
        # img = Image.composite(bg_shadow,bg, alpha)
        # img.save(imgSavePath+"bg.png")
    def CaptchaBgImg(self):
        """
          生成背景大图
        """
        x, y = self.x, self.y # 随机位置点
        mask_size = self.mask.size #获取蒙版大小
        crop = self.bg.crop((x, y, x + mask_size[0], y + mask_size[1])) 
        # 重新生成一个新的图层,跟 bg 一样大
        bg_shadow=Image.new("RGBA",self.bg.size,(0,0,0,0)) 
        bg_shadow.paste(crop,(x,y), mask=self.mask)     
        img_blender = Image.new('RGBA', bg_shadow.size, (0,0,0,0))   
        r, g, b, alpha = bg_shadow.split() 
        alpha = alpha.point(lambda i: i>0 and 255) 
        bg_shadow = Image.blend(img_blender, bg_shadow, 0.6)
        bg_shadow = Image.blend(img_blender, bg_shadow, 0.4) 
        # bg_shadow.save(self.savePath+str(self.timestamp)+'_b22g.png') # 保存 小的缺口图
        img = Image.composite(bg_shadow,self.bg, alpha)
        img.paste(self.mask_img_bg,(x,y), mask= self.mask_img_bg)
        img.save(self.savePath+str(self.timestamp)+'_bg.png') # 保存 小的缺口图
        # pixels = bg_shadow.load()
        # for i in range(bg_shadow.size[0]): # for every pixel:
        #     for j in range(bg_shadow.size[1]):
        #         if pixels[i,j] != (0,0,0,0):
        #             print("RBG",pixels[i,j])
        #             pixels[i,j] = (255, 255 ,255,255)
        #         pixels[i,j] = (255, 255 ,255,255)
        #img.save(self.savePath+str(self.timestamp)+"_bg.png")
    def getinfo(self):
        """ 返回坐标信息 """ 
        bg=random.choice(bglist)
        mask=random.choice(masklist)
        self.bg=  Image.open(bg) # 背景图
        self.x=random.randint(95,self.width-70)  # 随机坐标位置X轴生成
        self.y=random.randint(6,self.height-70) # 随机坐标位置Y轴生成
        self.timestamp=round(time.time()*1000000)
        self.mask = Image.open(self.maskimgPath+'mask_{}.png'.format(mask)) # 蒙板
        self.mask_bg = Image.open(self.maskimgPath+'mask_bg_{}.png'.format(mask)) # 蒙板
        self.mask_img_bg = Image.open(self.maskimgPath+'mask_img_bg_{}.png'.format(mask)) # 蒙板
        self.CgetGapDiagramImg()
        self.CaptchaBgImg()
        bg=self.bae64(self.savePath+str(self.timestamp)+"_bg.png")
        diagram=self.bae64(self.savePath+str(self.timestamp)+".png")
        # token={ 
        #     "x":self.x,
        #     "y":self.x,
        #     "timestamp":self.timestamp,
        # }
        return { 
            "x":self.x,
            "y":self.y,
            "bg":bg,#str(self.timestamp)+"_bg.png",
            "gap_diagram":diagram,#str(self.timestamp)+'.png',
            "timestamp":self.timestamp,
            "info":appsetting["author"]
            }
    def bae64(self,imgpath):
        with open(imgpath, 'rb') as f:
            image = f.read()
            image_base64 = str(base64.b64encode(image), encoding='utf-8')
        return image_base64

# def Captcha():
#     # width=imgconfig["width"]
#     # height=imgconfig["height"]  
#     # smallwidth=imgconfig["smallwidth"]
#     # smallheight=imgconfig["smallheight"]  
#     sde=ImgController(bgimgPath,maskimgPath,imgSavePath,height=height,width=width,smallwidth=smallwidth,smallheight=smallheight)  
#     sde.CgetGapDiagramImg()
#     sde.CaptchaBgImg()
#     return sde.getinfo()
# # Todo 测试 是否 符合要求
# if __name__=="__main__":     
#     width=imgconfig["width"]
#     height=imgconfig["height"]  
#     smallwidth=imgconfig["smallwidth"]
#     smallheight=imgconfig["smallheight"] 
#     for i in range(0,1):         
#         sde=ImgController(bgimgPath,maskimgPath,imgSavePath,height=height,width=width,imgurl="",smallwidth=smallwidth,smallheight=smallheight) 
#         sde.imgcompress()